package io.geekidea.boot.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.OrderByItem;
import io.geekidea.boot.framework.page.OrderMapping;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.business.dto.CntrolMeasureDto;
import io.geekidea.boot.business.entity.CntrolMeasure;
import io.geekidea.boot.business.mapper.CntrolMeasureMapper;
import io.geekidea.boot.business.query.CntrolMeasureQuery;
import io.geekidea.boot.business.service.CntrolMeasureService;
import io.geekidea.boot.business.vo.CntrolMeasureVo;
import io.geekidea.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 安全管控措施方案 服务实现类
 *
 * @author mr.wei
 * @since 2024-04-10
 */
@Slf4j
@Service
public class CntrolMeasureServiceImpl extends ServiceImpl<CntrolMeasureMapper, CntrolMeasure> implements CntrolMeasureService {

    @Autowired
    private CntrolMeasureMapper cntrolMeasureMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addCntrolMeasure(CntrolMeasureDto dto) {
        CntrolMeasure cntrolMeasure = new CntrolMeasure();
        BeanUtils.copyProperties(dto, cntrolMeasure);
        return save(cntrolMeasure);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCntrolMeasure(CntrolMeasureDto dto) {
        Long id = dto.getId();
        CntrolMeasure cntrolMeasure = getById(id);
        if (cntrolMeasure == null) {
            throw new BusinessException("安全管控措施方案不存在");
        }
        BeanUtils.copyProperties(dto, cntrolMeasure);
        return updateById(cntrolMeasure);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteCntrolMeasure(Long id) {
        return removeById(id);
    }

    @Override
    public CntrolMeasureVo getCntrolMeasureById(Long id) {
        return cntrolMeasureMapper.getCntrolMeasureById(id);
    }

    @Override
    public Paging<CntrolMeasureVo> getCntrolMeasurePage(CntrolMeasureQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<CntrolMeasureVo> list = cntrolMeasureMapper.getCntrolMeasurePage(query);
        Paging<CntrolMeasureVo> paging = new Paging<>(list);
        return paging;
    }
}
